package cn.edu.repository.impl;

import cn.edu.entity.UserEntity;
import cn.edu.repository.UserRepository;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession(){

        return this.sessionFactory.openSession();
    }

    public UserEntity load(Long id) {
        return (UserEntity) getCurrentSession().load(UserEntity.class,id);
    }

    public UserEntity get(Long id) {
        return (UserEntity) getCurrentSession().get(UserEntity.class,id);
    }

    public List<UserEntity> findAll() {
        Criteria criteria = getCurrentSession().createCriteria(UserEntity.class);
        List list = criteria.list();
        return list;
    }

    public void persist(UserEntity entity) {
        getCurrentSession().persist(entity);
    }

    public Long save(UserEntity entity) {
        return (Long)getCurrentSession().save(entity);
    }

    public void saveOrUpdate(UserEntity entity) {
        Session hbSession = getCurrentSession();
        hbSession.saveOrUpdate(hbSession.merge(entity));
    }

    public void delete(Long id) {
        UserEntity userEntity = load(id);
        getCurrentSession().delete(userEntity);
    }

    public void flush() {
        getCurrentSession().flush();
    }
}
